﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Elf.Data.Entity.Interfaces;
using Elf.Data.Entity.Management;
using System.ServiceModel;
using Elf.Common;

namespace Elf.Data.Entity
{
    /// <summary>
    /// RepositoryBase
    /// </summary>
    /// <typeparam name="TEntity">The type of the entity.</typeparam>
    /// <typeparam name="TContext">The type of the context.</typeparam>
    public abstract class RepositoryBase<TEntity, TContext>
        where TEntity : IEntityBase
        where TContext : ContextBase, new()
    {
        private DbContextManager<TContext> _dbContextManager;

        /// <summary>
        /// Initializes a new instance of the <see cref="RepositoryBase&lt;T&gt;"/> class.
        /// </summary>
        protected RepositoryBase() { }

        /// <summary>
        /// Returns the current DbContextManager instance. Encapsulated the 
        /// _objectContextManager field to show it as an association on the class diagram.
        /// </summary>
        private DbContextManager<TContext> DbContextManager
        {
            get { return _dbContextManager; }
            set { _dbContextManager = value; }
        }

        /// <summary>
        /// Returns a ContextBase object. 
        /// </summary>
        protected internal TContext DbContext
        {
            get
            {
                if (DbContextManager == null)
                    this.InstantiateObjectContextManager();

                return DbContextManager.DbContext;
            }
        }

        /// <summary>
        /// Instantiates the object context manager.
        /// </summary>
        private void InstantiateObjectContextManager()
        {
            if (OperationContext.Current == null)
                this.DbContextManager = (ScopedDbContextManager<TContext>)ActivatorExtension.CreateGenericInstance(typeof(ScopedDbContextManager<>), typeof(TContext));
            else
                this.DbContextManager = (WcfDbContextManager<TContext>)ActivatorExtension.CreateGenericInstance(typeof(WcfDbContextManager<>), typeof(TContext));
        }
    }
}
